from functools import wraps
from aiohttp import web


def add_cors_headers(handler):
    """为响应添加跨域头的装饰器"""

    @wraps(handler)
    async def wrapper(request: web.Request) -> web.Response:
        # 处理预检请求（OPTIONS）
        if request.method == "OPTIONS":
            return web.Response(
                headers={
                    "Access-Control-Allow-Origin": "*",  # 允许所有源（生产环境可指定具体域名）
                    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
                    "Access-Control-Allow-Headers": "Content-Type, X-Requested-With",
                    "Access-Control-Max-Age": "3600"
                }
            )

        # 处理实际请求
        response = await handler(request)

        # 为所有响应添加跨域头
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Credentials"] = "true"
        return response

    return wrapper
